from django.views.generic.base import TemplateView            # 导入模板视图
from .models import Type_1, Type_2, Product

# Create your views here.

# 分类查询视图
class ClassifView_template(TemplateView):
    template_name = 'classification.html'
    extra_context = {
        'title':'分类',
    }

    def get_context_data(self, **kwargs):
        # 获取查询参数
        sencond = self.kwargs.get('sencond')
        products = None
        current_title = '全部商品'

        # 获取所有一级分类
        first_categories = Type_1.objects.all()

        # 为每个一级分类获取其下的二级分类
        categories_data = []
        for category in first_categories:
            subcategories = Type_2.objects.filter(first_id=category)
            categories_data.append({
                'category': category,
                'subcategories': subcategories
            })
        # 查询所有商品
        if sencond is None:
            products = Product.objects.all()
        # 查询所有一级分类下的二级产品
        else:
            current_title = sencond
            products = Product.objects.filter(types__second=sencond)

        context = {
                'categories_data': categories_data,
                'current_title':current_title,
                'products': products ,
            }
        return context

# 详情页查询视图
class DetailsView(TemplateView):
    template_name = 'details.html'

    def get_context_data(self, **kwargs):
        # 创建字典
        context = super(DetailsView, self).get_context_data(**kwargs)
        pk_value = self.kwargs.get('pk')
        # 查询数据详情页
        product = Product.objects.get(id=pk_value)
        context['title'] = product.name
        context['product'] = product
        return context